package com.whfc.iot.mach.processor;

import com.whfc.common.util.JSONUtil;
import com.whfc.iot.mach.constant.MsgConst;
import com.whfc.iot.mach.entity.MachMsg0x03;
import com.whfc.iot.mach.entity.MachMsg0x83;
import com.whfc.iot.session.Session;
import com.whfc.iot.session.SessionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @Description: 0x03消息处理
 * @author: xugcheng
 * @version: 1.0
 * @date: 2019/9/9 9:53
 */
@Component
public class MachUpMsgProcessor0x03 implements MachUpMsgProcessor<MachMsg0x03> {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private SessionManager sessionManager;

    @Override
    public void processMsg(MachMsg0x03 reqMsg) {
        logger.info("处理0x03数据:{}", JSONUtil.toString(reqMsg));
        Integer deviceId = reqMsg.getDeviceId();
        Integer deviceType = reqMsg.getDeviceType();

        //构造0x83
        MachMsg0x83 resMsg = new MachMsg0x83();
        resMsg.setStartFlag(MsgConst.START_FLAG);
        resMsg.setDeviceType(deviceType);
        resMsg.setDeviceId(deviceId);
        resMsg.setSeq(reqMsg.getSeq() + 1);
        resMsg.setCmd(MsgConst.DOWNSTREAM_CMD_0x83);
        resMsg.setTime(new Date());

        //响应0x83
        Session session = sessionManager.getSessionByDeviceId(deviceId);
        session.getChannel().writeAndFlush(resMsg).addListener(future -> {
            logger.info("0x83发送结果,deviceId={},isDone={},isSuccess={}", deviceId, future.isDone(), future.isSuccess());
        });
    }
}
